<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">控制台</el-breadcrumb-item>
      <el-breadcrumb-item><b>业主信息管理</b></el-breadcrumb-item>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
    </el-breadcrumb>
    <hr>

    <!-- 头部的卡片 -->
    <el-card style="font-size: 20px;font-family: 'Helvetica Nee',serif">
      <b>人员管理</b>
      <p style="font-size: 15px">用于管理小区里每个住户的基本信息，包括业主、家庭成员及租户等信息</p>
    </el-card>

    <!-- 数据相关的卡片 -->
    <el-card class="box-card">
      <div class="card-header">
        <el-row>
          <!-- 添加按钮 -->
          <el-col :span="18">
            <Button type="success" icon="md-add" @click="dialogFormVisibleAdd = true">添加</Button>
            <span style="margin-left: 10px;"></span>
            <Button type="success" icon="md-list-box" @click="dialogExeclAdd = true">通过Execl批量添加</Button>
            <span style="margin-left: 10px;"></span>            
            <Button type="dashed" icon="md-arrow-down" @click="loadExeclData()" style="display: inline;">导出全部数据到Excel</Button>
            <span style="margin-left: 10px;"></span>
            <Button v-if="showDeleteButton" type="dashed" icon="md-arrow-down" @click="loadExeclData(selectionItem)">导出选中数据到Excel</Button>
            <span v-if="showDeleteButton" style="margin-right: 10px;"></span>
            <Button v-if="showDeleteButton" type="error" icon="md-trash" @click="deleteByIds()">批量删除</Button>
          </el-col>
          <!-- 搜索框 -->
          <el-col :span="4">            
            <Input search style="width: 260px;" enter-button placeholder="请输入搜索的内容" @on-search="search()"/>            
          </el-col>
          <!-- 根据小区查询下拉框 -->
          <el-col :span="2" style="text-align: right;">
            <Dropdown @on-click="selectByCommunity">
                <Button type="primary">
                  根据小区查询 <Icon type="ios-arrow-down"></Icon>
                </Button>
                <DropdownMenu slot="list">
                    <DropdownItem :name="null">
                      所有小区
                    </DropdownItem>
                    <DropdownItem v-for="community, index in communityList" :key="index" :name="community.code">
                      {{ community.name }}
                    </DropdownItem>
                </DropdownMenu>
            </Dropdown>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loadTable" :border="true" ref="multipleTable" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column fixed prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="communityName" label="所属小区" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="propertyName" label="房产名称" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="peopleName" label="成员名称" width="100"></el-table-column>
        <el-table-column prop="idNumber" label="身份证号码" width="200"></el-table-column>
        <el-table-column prop="telephone" label="联系方式" width="140"></el-table-column>
        <el-table-column prop="job" label="职业" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="140"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.gender == 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="describes" label="描述" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" width="180"></el-table-column>
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <ButtonGroup>
              <Button type="info" icon="md-create" @click="showUpdateDialog(scope.row)"></Button>
              <Button type="error" icon="md-trash" @click="deleteIds = [scope.row.id]; deleteByIds()"></Button>
            </ButtonGroup>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <!-- 分页查询 -->
        <Page :total="total" show-elevator show-sizer :current="currentPage" :page-size="pageSize" @on-change="changePage" @on-page-size-change="changePageSize"/>
      </div>

    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisibleUpdate" center>
      <el-form :model="editFormUpdate" ref="editFormUpdate">
          <el-form-item label="所属小区" prop="communityCode" :rules="[{required: true, message: '请完善所属小区'}]">
              <el-select v-model="editFormUpdate.communityCode" placeholder="请选择" border>
                <el-option v-for="item, index in communityList" :key="index" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="所属房产" prop="propertyCode" :rules="[{required: true, message: '请完善所属房产'}]">
            <el-select v-model="editFormUpdate.propertyCode" placeholder="请选择" border>
              <el-option v-for="item, index in propertyList" :key="index" :label="item.name" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="成员名称" prop="peopleName" :rules="[{required: true, message: '请完善成员名称'}]">
            <el-input v-model="editFormUpdate.peopleName"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber" :rules="[{required: true, message: '请完善身份证号码'}]">
            <el-input v-model="editFormUpdate.idNumber"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="telephone" :rules="[{required: true, message: '请完善联系方式'}]">
            <el-input v-model="editFormUpdate.telephone"></el-input>
          </el-form-item>
          <el-form-item label="职业" prop="job" :rules="[{required: true, message: '请完善职业'}]">
            <el-input v-model="editFormUpdate.job"></el-input>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthday" :rules="[{required: true, message: '请完善出生日期'}]">
            <el-date-picker type="date" placeholder="选择日期" v-model="editFormUpdate.birthday"></el-date-picker>
          </el-form-item>
          <el-form-item label="性别" prop="gender" :rules="[{required: true, message: '请完善性别'}]">
            <el-radio-group v-model="editFormUpdate.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述" prop="describes" :rules="[{required: true, message: '请完善描述'}]">
            <el-input type="textarea" :rows="2" v-model="editFormUpdate.describes"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="update('editFormUpdate')">确 定</el-button>
            <el-button @click="dialogFormVisibleUpdate = false">关 闭</el-button>
          </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加弹窗 -->
    <el-dialog title="添加" :visible.sync="dialogFormVisibleAdd" center>
      <el-form :model="editFormAdd" ref="editFormAdd">
          <el-form-item label="所属小区" prop="communityCode" :rules="[{required: true, message: '请完善所属小区'}]">
              <el-select v-model="editFormAdd.communityCode" placeholder="请选择" border>
                <el-option v-for="item, index in communityList" :key="index" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="所属房产" prop="propertyCode" :rules="[{required: true, message: '请完善所属房产'}]">
            <el-select v-model="editFormAdd.propertyCode" placeholder="请选择" border>
              <el-option v-for="item, index in propertyList" :key="index" :label="item.name" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="成员名称" prop="peopleName" :rules="[{required: true, message: '请完善成员名称'}]">
            <el-input v-model="editFormAdd.peopleName"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber" :rules="[{required: true, message: '请完善身份证号码'}]">
            <el-input v-model="editFormAdd.idNumber"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="telephone" :rules="[{required: true, message: '请完善联系方式'}]">
            <el-input v-model="editFormAdd.telephone"></el-input>
          </el-form-item>
          <el-form-item label="职业" prop="job" :rules="[{required: true, message: '请完善职业'}]">
            <el-input v-model="editFormAdd.job"></el-input>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthday" :rules="[{required: true, message: '请完善出生日期'}]">
            <el-date-picker type="date" placeholder="选择日期" v-model="editFormAdd.birthday"></el-date-picker>
          </el-form-item>
          <el-form-item label="性别"  prop="gender" :rules="[{required: true, message: '请完善性别'}]">
            <el-radio-group v-model="editFormAdd.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述" prop="describes" :rules="[{required: true, message: '请完善描述'}]">
            <el-input type="textarea" :rows="2" v-model="editFormAdd.describes"></el-input>
          </el-form-item>
          <el-form-item center>       
            <el-button type="primary" @click="add('editFormAdd')">确 定</el-button>
            <el-button @click="dialogFormVisibleAdd = false">关 闭</el-button>
          </el-form-item>
      </el-form>  
    </el-dialog>

    <el-dialog title="通过Execl批量添加" :visible.sync="dialogExeclAdd" center :close-on-click-modal="false">
      <el-upload :file-list="fileList" :action="this.host + '/owners/uploadExecl'" :before-upload="() => uploadDisabled = true" :on-success="uploadSuccess" drag style="text-align: center;" accept=".xlsx,.xls,.csv" :on-exceed="handleExceed" :disabled="uploadDisabled" :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传Execl文件</div>
      </el-upload>
    </el-dialog>

    <!-- 返回顶部按钮 -->
    <BackTop></BackTop>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "index",
  data() {
    return {
      fileList: [],
      loadTable: false,
      showDeleteButton: false,
      selectionItem: [],
      editFormUpdate: {},
      editFormAdd: {},
      dialogFormVisibleUpdate: false,
      dialogFormVisibleAdd: false,
      communityList: [],
      propertyList: [],
      communityCode: null,
      searchText: "",
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogExeclAdd: false,
      uploadDisabled: false,
      excelAllData: []
    }
  },
  methods: {
    // 搜索方法
    search() {

    },
    exportExcel(excelData) {
      this.$message.info("导出数据中...");
      // 生成 workbook
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(excelData);
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      // 生成二进制流并保存文件
      const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([wbout], { type: 'application/octet-stream' });
      saveAs(blob, location.pathname.split("/")[1] + "-" + location.pathname.split("/")[2] + ".xlsx");
    },
    // 导出Execl方法
    loadExeclData(excelData) {
      if (excelData) { 
        this.exportExcel(excelData);
      } else {
        let url = this.host + "/owners/list";
        this.axios.get(url).then((response) => {
          if (response.data.statusCode == 2000) {
            this.exportExcel(response.data.data.records);
          } else {
            this.$message.error("导出数据出错了！");
          }
        });
      }    
    },
    //上传成功函数
    uploadSuccess(response) {
      if (response.statusCode == 2000) {
        this.$message.success(response.data);
        this.uploadDisabled = false;
        this.dialogExeclAdd = false;
      } else {
        this.$message.error(response.message);
      }
      this.fileList = [];
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件！`);
    },
    // 添加数据方法
    add(formName) {
      this.$refs[formName].validate((valid) => {        
        if (valid) {
          let url = this.host + "/owners/add";
          this.axios.post(url, JSON.stringify(this.editFormAdd), {
            headers: {
              "Content-Type": "application/json"
            }}).then((response) => {
              if (response.data.statusCode == 2000) {
                this.$message.success(response.data.data);
                this.dialogFormVisibleAdd = false;
                this.loadDataList();
              } else {
                this.$message.error(response.data.message);
              }
          });          
        } else {
          this.$message.error("请完善内容！");
        }
      });
    },
    // 批量删除
    deleteByIds() {
      // 打开加载状态
      this.loadTable = true;
      let url = this.host + "/owners/delete?" + this.selectionItem.map(item => `ids=${encodeURIComponent(item.id)}`).join('&');
      this.axios.get(url).then((response) => {
        if (response.data.statusCode == 2000) {
          this.$message.success(response.data.data);
          this.loadDataList();
          // 取消加载状态 
          this.loadTable = false;      
          this.showDeleteButton = false;
        } else {
          this.$message.error("删除失败，请稍后再试！");
        }
      });     
    },
    // 表格多选选择后触发的方法
    handleSelectionChange(rows) {
      this.selectionItem = [];
      if (rows.length === 0) {
        this.showDeleteButton = false;
        return;
      }
      this.showDeleteButton = true;
      for (let item of rows) {
        this.selectionItem.push(item);
      }
    },
    // 打开弹窗方法
    showUpdateDialog(row) {
      this.dialogFormVisibleUpdate = true;
      this.editFormUpdate = row;
    },
    // 修改数据的方法
    update(formName) {
      this.$refs[formName].validate((valid) => {        
        if (valid) {
          let url = this.host + "/owners/update";
          this.axios.post(url, JSON.stringify(this.editFormUpdate), {
            headers: {
              "Content-Type": "application/json"
            }}).then((response) => {
              if (response.data.statusCode == 2000) {
                this.$message.success(response.data.data);
                this.dialogFormVisibleUpdate = false;
                this.loadDataList();
              } else {
                this.$message.error(response.data.message);
              }
          });
        } else {
          this.$message.error("请完善内容！");
        }
      });            
    },
    // 选择小区后调用的方法
    selectByCommunity(communityCode) {
      this.communityCode = communityCode;
      this.pageSize = 10;
      this.currentPage = 1;
      this.loadDataList();
    },
    // 改变第几页后调用的方法
    changePage(pageNum) {
      this.currentPage = pageNum;
      this.loadDataList();
    },
    // 改变每页多少条数据后调用的方法
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.loadDataList();
    },
    // 加载当前模块数据
    loadDataList() {
      this.loadTable = true;      
      let url = this.host + "/owners/list?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize;
      if (this.communityCode != null) {
        url = this.host + "/owners/list?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&communityCode=" + this.communityCode;
      }
      this.axios.get(url).then((response) => {
        if (response.data.statusCode == 2000) {
          this.tableData = response.data.data.records;
          this.currentPage = response.data.data.current;
          this.pageSize = response.data.data.size;
          this.total = response.data.data.total;
        } else {
          this.$message.error("加载数据出错了！");
        }
        this.loadTable = false;
      });      
    },
    // 加载所有房产数据
    loadPropertyList() {
      let url = this.host + "/property/list";
      this.axios.get(url).then((response) => {
        if (response.data.statusCode == 2000) {
          this.propertyList = response.data.data.records;
        } else {
          this.$message.error("加载数据出错了！");
        }
      });
    },
    // 加载所有小区数据
    loadCommunityList() {
      let url = this.host + "/community/list";
      this.axios.get(url).then((response) => {
        if (response.data.statusCode == 2000) {
          this.communityList = response.data.data.records;
        } else {
          this.$message.error("加载数据出错了！");
        }
      });
    }
  },
  mounted() {
    // 页面初始化后调用加载本模块数据和小区等的所有数据
    this.loadDataList();
    this.loadCommunityList();
    this.loadPropertyList();
  }
}
</script>

<style scoped>
.card-header {
  margin-bottom: 20px;
}

.block {
  text-align: center;
  margin-top: 10px;
}
</style>
